function getParameterByName(name, url) {
    url = url || window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

const uroot = getParameterByName('uroot');

var uid = getParameterByName('uid');
const id = parseInt(uid, 10);

var name = getParameterByName('uname');

// 调整后的模块样式
const modules = [
    {id: "VIS", name: "可视化大厅", radius: 320, angle: 30},
    {id: "FIN", name: "智能后台", radius: 320, angle: 102},
    {id: "VHC", name: "数据模拟", radius: 320, angle: 174},
    {id: "IMP", name: "数据处理", radius: 320, angle: 246},
    {id: "USER", name: "用户管理", radius: 320, angle: 318}
];
const container = document.querySelector('.container');

modules.forEach(module => {
    const node = document.createElement('div');
    node.className = 'node';

    // 根据 uroot 的值动态设置模块名称
    if (module.id === "USER") {
        if (uroot === "2") {
            node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">个人账单列表</p>`;
        } else {
            node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">${module.name}</p>`;
        }
    } else if (module.id === "VHC") {
        if (uroot === "2" || uroot === "4") {
            node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">个人中心</p>`;
        } else if (uroot === "8") {
            node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">汽车账单列表</p>`;
        } else {
            node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">${module.name}</p>`;
        }
    } else {
        node.innerHTML = `<p style="font-size: 1.4em; color: #00f7ff; text-shadow: 0 0 5px rgba(0, 247, 255, 0.5); letter-spacing: 1px;">${module.name}</p>`;
    }

    // 添加点击事件
    if (module.id === "VIS") {
        node.style.cursor = 'pointer';
        node.addEventListener('click', () => {
            window.location.href = "index.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
        });
    }
    if (module.id === "FIN") {
        node.style.cursor = 'pointer';
        node.addEventListener('click', () => {
            window.location.href = "manage.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
        });
    }
    if (module.id === "VHC") {
        node.style.cursor = 'pointer';
        node.addEventListener('click', () => {
            if (uroot === "8") {
                window.location.href = "dataroot.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
            }
        });
    }
    if (module.id === "IMP") {
        node.style.cursor = 'pointer';
        node.addEventListener('click', () => {
            window.location.href = "data.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
        });
    }
    if (module.id === "USER") {
        node.style.cursor = 'pointer';
        node.addEventListener('click', () => {
            // 根据 uroot 的值动态设置跳转地址
            if (uroot === "2") {
                window.location.href = "datauser.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
            } else if (uroot === "4" || uroot === "8") {
                window.location.href = "user.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name)
            }
        });
    }

    // 计算坐标
    const angleOffset = -35;
    const effectiveAngle = module.angle + angleOffset;
    const radian = (effectiveAngle - 90) * Math.PI / 180;
    const x = Math.cos(radian) * module.radius;
    const y = Math.sin(radian) * module.radius;

    node.style.left = `calc(50% + ${x}px)`;
    node.style.top = `calc(50% + ${y}px)`;
    node.style.transform = `translate(-50%, -50%)`;

    // 创建量子连接线
    const line = document.createElement('div');
    line.className = 'quantum-line';
    line.style.width = `${module.radius * 0.85}px`;
    line.style.left = '50%';
    line.style.top = '50%';

    line.style.transform = `rotate(${effectiveAngle}deg)`;

    container.appendChild(line);
    container.appendChild(node);
});

// 粒子系统
function createParticles() {
    const particles = document.getElementById('particles');
    for (let i = 0; i < 100; i++) {
        const p = document.createElement('div');
        p.className = 'particle';
        p.style.cssText = `
          width: ${Math.random() * 3}px;
          height: ${Math.random() * 20}px;
          left: ${Math.random() * 100}%;
          opacity: ${Math.random() * 0.5};
          animation-duration: ${5000 + Math.random() * 5000}ms;
          animation-delay: ${Math.random() * 3000}ms;
        `;
        particles.appendChild(p);
    }
}

createParticles();

// 节点交互
document.querySelectorAll('.node').forEach(node => {
    node.addEventListener('mouseenter', () => {
        const sparks = document.createElement('div');
        sparks.style.cssText = `
          position: absolute;
          width: 100%;
          height: 100%;
          background: radial-gradient(circle,
            hsl(${Math.random() * 360}, 100%, 70%) 0%,
            transparent 70%);
          mix-blend-mode: screen;
          animation: sparkle 0.5s linear;
        `;
        node.appendChild(sparks);
        setTimeout(() => sparks.remove(), 500);
    });
});

// 随机流光
setInterval(() => {
    const spark = document.createElement('div');
    spark.style.cssText = `
        position: absolute;
        width: 20px;
        height: 2px;
        background: linear-gradient(to right, transparent, #00f7ff, transparent);
        left: ${Math.random() * 100}%;
        top: ${Math.random() * 100}%;
        animation: flowHorizontal 2s linear;
      `;
    container.appendChild(spark);
    setTimeout(() => spark.remove(), 2000);
}, 500);

// 添加额外动画
const style = document.createElement('style');
style.textContent = `
        @keyframes flowHorizontal {
        0% { transform: translateX(-100%); opacity: 0; }
        50% { opacity: 1; }
        100% { transform: translateX(200%); opacity: 0; }
    }
        @keyframes sparkle {
        0% { opacity: 1; transform: scale(1); }
        100% { opacity: 0; transform: scale(2); }
    }
        `;
document.head.appendChild(style);

const urlParams = new URLSearchParams(window.location.search);
const root = urlParams.get('uroot');
const nowUname = sessionStorage.getItem("nowUname");

if (nowUname) {
    document.getElementById('currentUname').textContent = nowUname;
} else {
    console.warn('未获取到用户名信息');
    document.getElementById('currentUname').textContent = '游客';
}

// 检查用户权限
if (uroot === null) {
    alert('身份认证失败，请重新登录');
    window.location.href = 'login.html';
}


// 悬浮窗和对话框的逻辑
const suspensionWindow = document.createElement('div');
suspensionWindow.className = 'suspension-window';
suspensionWindow.innerHTML = `<img src="" alt="">`; // 替换为你的图片路径

document.body.appendChild(suspensionWindow);

const chatContainer = document.createElement('div');
chatContainer.className = 'chat-container';
chatContainer.innerHTML = `
    <div class="chat-header">
        <span>AI助手</span>
        <button class="close-button">&times;</button>
    </div>
    <div class="chat-messages" id="chat-messages"></div>
    <div class="chat-input-area">
        <input type="text" id="user-input" placeholder="输入消息...">
        <button class="send-button" onclick="sendMessage()">发送</button>
    </div>
`;

document.body.appendChild(chatContainer);

// 悬浮窗点击事件
suspensionWindow.addEventListener('click', () => {
    chatContainer.classList.toggle('visible');
});

// 关闭按钮点击事件
chatContainer.querySelector('.close-button').addEventListener('click', () => {
    chatContainer.classList.remove('visible');
});

// 添加消息到对话框
function displayMessage(text, type) {
    const messages = document.getElementById('chat-messages');
    const message = document.createElement('div');
    message.className = `message ${type}-message`;
    message.textContent = text;
    messages.appendChild(message);
    messages.scrollTop = messages.scrollHeight;
}

// // 发送消息到后端接口（本地部署的ai）
// function sendMessage() {
//     const userInput = document.getElementById('user-input').value.trim();
//     if (!userInput) return;
//
//     // 显示用户消息
//     displayMessage(userInput, 'user');
//     document.getElementById('user-input').value = '';
//
//     // 调用API获取AI回复
//     fetch('/api/ask', {
//         method: 'POST',
//         headers: {
//             'Content-Type': 'application/json',
//         },
//         body: JSON.stringify({ question: userInput })
//     })
//         .then(response => response.json())
//         .then(data => {
//             displayMessage(data.answer, 'ai');
//         })
//         .catch(error => {
//             console.error('Error:', error);
//             displayMessage('抱歉，发生了一些错误，请稍后再试。', 'ai');
//         });
// }


// 发送消息到阿里云通义千问-Turbo API
function sendMessage() {
    const userInput = document.getElementById('user-input').value.trim();
    if (!userInput) return;

    // 显示用户消息
    displayMessage(userInput, 'user');
    document.getElementById('user-input').value = '';

    // 调用API获取AI回复
    fetch('https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + 'sk-9d92efc3d1144fcfb18f6761cb7b552d', // 替换为你的 API 密钥
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            "model": "qwen-turbo", // 使用通义千问-Turbo 模型
            "temperature": 1.0,  // 添加 temperature 参数
            "messages": [
                {
                    "role": "system",
                    "content": "You are a helpful assistant."
                },
                {
                    "role": "user",
                    "content": userInput
                },
            ],
        })
    })
        .then(response => response.json())
        .then(data => {
            displayMessage(data.choices[0].message.content, 'ai');
        })
        .catch(error => {
            console.error('Error:', error);
            displayMessage('抱歉，发生了一些错误，请稍后再试。', 'ai');
        });
}

// 回车发送消息
document.getElementById('user-input').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

// 回车发送消息
document.getElementById('user-input').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

// 拖动功能
let isDragging = false;
let startX, startY, initialX, initialY;

// 悬浮窗拖动
suspensionWindow.addEventListener('mousedown', (e) => {
    isDragging = true;
    startX = e.clientX - suspensionWindow.offsetLeft;
    startY = e.clientY - suspensionWindow.offsetTop;
    initialX = suspensionWindow.offsetLeft;
    initialY = suspensionWindow.offsetTop;
    suspensionWindow.classList.add('dragging');
});

document.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    e.preventDefault();
    const x = e.clientX - startX;
    const y = e.clientY - startY;
    suspensionWindow.style.left = `${x}px`;
    suspensionWindow.style.top = `${y}px`;

    // 检查是否靠近边缘
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const suspensionWidth = suspensionWindow.offsetWidth;
    const suspensionHeight = suspensionWindow.offsetHeight;

    if (x < suspensionWidth / 2) {
        suspensionWindow.style.left = `-${suspensionWidth / 2}px`;
    } else if (x > windowWidth - suspensionWidth / 2) {
        suspensionWindow.style.left = `${windowWidth - suspensionWidth / 2}px`;
    }

    if (y < suspensionHeight / 2) {
        suspensionWindow.style.top = `-${suspensionHeight / 2}px`;
    } else if (y > windowHeight - suspensionHeight / 2) {
        suspensionWindow.style.top = `${windowHeight - suspensionHeight / 2}px`;
    }
});

document.addEventListener('mouseup', () => {
    isDragging = false;
    suspensionWindow.classList.remove('dragging');
});

// 对话框拖动
let isChatDragging = false;
let chatStartX, chatStartY, chatInitialX, chatInitialY;

chatContainer.querySelector('.chat-header').addEventListener('mousedown', (e) => {
    isChatDragging = true;
    chatStartX = e.clientX - chatContainer.offsetLeft;
    chatStartY = e.clientY - chatContainer.offsetTop;
    chatInitialX = chatContainer.offsetLeft;
    chatInitialY = chatContainer.offsetTop;
    chatContainer.classList.add('dragging');
});

document.addEventListener('mousemove', (e) => {
    if (!isChatDragging) return;
    e.preventDefault();
    const x = e.clientX - chatStartX;
    const y = e.clientY - chatStartY;
    chatContainer.style.left = `${x}px`;
    chatContainer.style.top = `${y}px`;

    // 悬浮窗跟随对话框
    const chatWidth = chatContainer.offsetWidth;
    const chatHeight = chatContainer.offsetHeight;
    const chatLeft = parseInt(chatContainer.style.left) || chatContainer.offsetLeft;
    const chatTop = parseInt(chatContainer.style.top) || chatContainer.offsetTop;

    suspensionWindow.style.left = `${chatLeft + chatWidth - suspensionWindow.offsetWidth - 20}px`;
    suspensionWindow.style.top = `${chatTop + chatHeight - suspensionWindow.offsetHeight - 20}px`;
});

document.addEventListener('mouseup', () => {
    isChatDragging = false;
    chatContainer.classList.remove('dragging');
});
